//
//  OtherCart.m
//  cutter
//
//  Created by mac on 16/3/3.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherOrder.h"
#import "OtherCart.h"
#import "OtherCenter.h"
//
//
@interface OtherCartCustomText : UITextField
@end
@implementation OtherCartCustomText
- (CGRect)textRectForBounds:(CGRect)bounds{
    CGRect rect = [super textRectForBounds:bounds];
    return CGRectInset(rect, 5, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds{
    CGRect rect = [super editingRectForBounds:bounds];
    return CGRectInset(rect, 5, 0);
}
@end
//
//
@interface OtherCartCustom : UITableViewController
@property (weak, nonatomic) IBOutlet UITextView *contentView;
@property (weak, nonatomic) IBOutlet UITextField *priceView;
@property(nonatomic, copy) blockEvent onSelected;
@end
@implementation OtherCartCustom
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.presentationController) {
        UIView *parent = [[self.navigationController view] superview];
        if (parent) {
            [parent.layer setCornerRadius:6];
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.1;
    }
    return tableView.sectionHeaderHeight;
}
- (IBAction)exitTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
- (IBAction)doneTouch:(id)sender {
    if (self.onSelected) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setValue:self.contentView.text forKey:@"content"];
        [data setValue:self.priceView.text forKey:@"price"];
        //
        self.onSelected(self, data);
    }
}
@end
//
//
@interface OtherCartHead : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *selectView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@property (nonatomic, strong) UITreeNode *node;
@end
@implementation OtherCartHead
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:self.node.select animated:animated];
    [self.selectView setSelected:self.node.select];
}
@end
//
//
@interface OtherCartCellCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UIButton *selectView;
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@property (weak, nonatomic) IBOutlet UILabel *sizeView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *totalView;
@property (weak, nonatomic) IBOutlet UILabel *countView;
@property (weak, nonatomic) IBOutlet UIButton *subView;
@property (weak, nonatomic) IBOutlet UIButton *addView;
@property (nonatomic, strong) UITreeNode *node;
@end
@implementation OtherCartCellCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:self.node.select animated:animated];
    [self.selectView setSelected:self.node.select];
}
@end
//
//
@implementation OtherCart
+(id)convertData:(NSArray*)data{
    id suitsKey = nil;
    id groupKey = nil;
    NSMutableDictionary *val0 = [NSMutableDictionary dictionary];
    for(id item in data){
        id uuid = [item objectForKey:@"uuid"];
        if (uuid) {
            if ([[item objectForKey:@"productid"] intValue] > 0) {
                id suit = [item objectForKey:@"suit"];
                if (suit && [suit isKindOfClass:NSDictionary.class]) {
                    suitsKey = [suit objectForKey:@"suitname"];
                    if ([[item objectForKey:@"hardpacked"] boolValue]) {
                        groupKey = @"硬装";
                    }else{
                        groupKey = @"软装";
                    }
                }else{
                    suitsKey=@"单品";
                    groupKey=@"";
                }
            }else{
                suitsKey = @"自定义";
                groupKey = @"";
            }
        }else{
            uuid = [item objectForKey:@"productid"];
            suitsKey = @"";
            groupKey = @"";
        }
        //空间
        NSMutableDictionary *suits = [val0 objectForKey:suitsKey];
        if (suits == nil) {
            suits = [NSMutableDictionary dictionary];
            [val0 setValue:suits forKey:suitsKey];
        }
        //分组
        NSMutableDictionary *group = [suits objectForKey:groupKey];
        if (group == nil) {
            group = [NSMutableDictionary dictionary];
            [suits setValue:group forKey:groupKey];
        }
        //产品
        [group setValue:item forKey:uuid];
    }
    //
    NSMutableArray *array = [NSMutableArray array];
    for (id key1 in val0.allKeys) {
        NSDictionary *val1 = [val0 objectForKey:key1];
        if (val1) {
            NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
            NSMutableArray *arr1 = [NSMutableArray array];
            [dic1 setValue:arr1 forKey:@"items"];
            [dic1 setValue:key1 forKey:@"name"];
            for (id key2 in val1.allKeys) {
                NSDictionary *val2 = [val1 objectForKey:key2];
                if (val2) {
                    NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
                    [dic2 setValue:val2.allValues forKey:@"items"];
                    [dic2 setValue:key2 forKey:@"name"];
                    [arr1 addObject:dic2];
                }
            }
            [array addObject:dic1];
        }
    }
    return array;
}
//
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.delView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.selView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.tableView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.tableView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.tableView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    OtherCenter *center = (id)self.splitViewController;
    if ([center isKindOfClass:OtherCenter.class] && center.userCenterCtrl) {
        [self setClient:center.userCenterCtrl.client];
        [self headerRefresh:nil];
    }
}
-(void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.tableView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak OtherCart *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (this.data == nil) {
            [this setSource:[AppData userCart:this.client]];
        }else{
            [this setSource:this.data];
        }
        UITreeNode *root = [this makeNodesWithData:[NSDictionary dictionaryWithObject:[OtherCart convertData:this.source] forKey:@"items"] level:-1];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            //
            [this.tableView setRootNode:root];
            [this.selView setSelected:NO];
            [this updata];
        });
    });
}
-(UITreeNode*)makeNodesWithData:(id)data level:(NSInteger)level{
    static NSInteger identify = 0;
    if ([data isKindOfClass:NSDictionary.class]) {
        UITreeNode *nodes=[[UITreeNode alloc] init];
        nodes.idetify = identify++;
        nodes.level = level;
        nodes.expand = YES;
        nodes.select = NO;
        nodes.value = data;
        //子级列出
        id child = [data objectForKey:@"items"];
        if (child) {
            for (id item in child) {
                [nodes addNode:[self makeNodesWithData:item level:level+1]];
            }
        }
        return nodes;
    }
    return nil;
}
//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak OtherCart *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *temp = segue.destinationViewController;
        if ([[temp.viewControllers firstObject] isKindOfClass:OtherCartCustom.class]) {
            OtherCartCustom *ctrl = [temp.viewControllers firstObject];
            [ctrl setOnSelected:^(id target, id result){
                if (result) {
                    NSMutableDictionary *post = [NSMutableDictionary dictionary];
                    [post setValue:[TMJSON stringify:result] forKey:@"json"];
                    [post setValue:@(0) forKey:@"productid"];
                    //
                    [AppData userAddCart:post client:this.client];
                }
                [this dismissViewControllerAnimated:YES completion:nil];
                [this headerRefresh:nil];
            }];
        }
    }
    if ([segue.destinationViewController isKindOfClass:OtherOrder.class]) {
        NSMutableArray *select = [NSMutableArray array];
        NSArray *selected = [self.tableView visibleNodes];
        for (UITreeNode *node in selected) {
            if (node.select && node.level == 2) {
                [select addObject:node.value];
            }
        }
        OtherOrder *temp = segue.destinationViewController;
        [temp setClient:self.client];
        [temp setSource:select];
    }
}
//
-(void)treeView:(UITreeView *)treeView expandRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    [self selectNode:node];
    [self updata];
}
-(void)treeView:(UITreeView *)treeView collapseRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    [self deselectNode:node];
    [self updata];
}
-(UITableViewCell *)treeView:(UITreeView *)treeView cellForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level == 0) {
        OtherCartHead *cell = [treeView dequeueReusableCellWithIdentifier:@"headIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        [cell setNode:node];
        return cell;
    }
    if (node.level == 1) {
        OtherCartHead *cell = [treeView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        [cell setNode:node];
        return cell;
    }
    id detail = [node.value objectForKey:@"product_detail"];
    if ([[node.value objectForKey:@"productid"] intValue] > 0) {
        OtherCartCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        [cell.subView addTarget:self action:@selector(countTouch:) forControlEvents:UIControlEventTouchUpInside];
        [cell.addView addTarget:self action:@selector(countTouch:) forControlEvents:UIControlEventTouchUpInside];
        [cell.totalView setText:[AppData totalToString:[detail objectForKey:@"price"] count:[node.value objectForKey:@"number"]]];
        [cell.countView setText:[AppData objToString:[node.value objectForKey:@"number"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
        [cell.nameView setText:[AppData objToString:[detail objectForKey:@"productname"] lable:nil]];
        [cell.sizeView setText:[AppData objToString:[detail objectForKey:@"productsn"] lable:nil]];
        [AppData loadImage:[detail objectForKey:@"thumb400_jpg"] view:cell.iconView];
        [cell setNode:node];
        return cell;
    }
    //
    OtherCartCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"otherIdentifier"];
    [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
    [cell.nameView setText:[AppData objToString:[detail objectForKey:@"remark"] lable:nil]];
    [cell setNode:node];
    return cell;
}
-(CGFloat)treeView:(UITreeView *)treeView heightForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level < 2) {
        if ([[node.value objectForKey:@"name"] isEqualToString:@""]) {
            return 0;
        }
        return 40;
    }
    return 119;
}
//
-(void)countTouch:(UIButton*)sender{
    UIView *temp = sender;
    while (temp) {
        if ([temp isKindOfClass:OtherCartCellCell.class]) {
            break;
        }
        temp = [temp superview];
    }
    //
    if (temp) {
        OtherCartCellCell *cell = (id)temp;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        if (indexPath) {
            NSNumber *number = [cell.node.value objectForKey:@"number"];
            NSInteger count = [number intValue];
            if (sender == cell.addView) {
                [cell.node.value setValue:[NSNumber numberWithInteger:count+1] forKey:@"number"];
            }else{
                if (count>1) {
                    [cell.node.value setValue:[NSNumber numberWithInteger:count-1] forKey:@"number"];
                }
            }
            if ([AppData userEditCart:cell.node.value]) {
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [cell.node.value setValue:number forKey:@"number"];
            }
        }
        [self updata];
    }
}
-(void)selectNode:(UITreeNode*)node{
    if (node) {
        [node setSelect:YES];
        for (UITreeNode *item in node.nodes) {
            [self selectNode:item];
        }
    }
}
-(void)deselectNode:(UITreeNode*)node{
    if (node) {
        [node setSelect:NO];
        for (UITreeNode *item in node.nodes) {
            [self deselectNode:item];
        }
    }
}
-(id)deleteNode:(UITreeNode*)node{
    NSMutableArray *array = [NSMutableArray array];
    if (node) {
        if (node.select && node.level == 2) {
            [array addObject:node.value];
            [node.parent removeNode:node];
        }else{
            for (UITreeNode *item in node.nodes) {
                [array addObjectsFromArray:[self deleteNode:item]];
            }
        }
    }
    return array;
}
-(void)ctrlTouch:(UIButton*)sender{
    if (self.selView == sender) {
        [sender setSelected:!sender.selected];
        //
        if (sender.selected) {
            [self selectNode:self.tableView.rootNode];
        }else{
            [self deselectNode:self.tableView.rootNode];
        }
    }
    if (self.delView == sender) {
        NSArray *carts = [self deleteNode:self.tableView.rootNode];
        [AppData userDeleteCart:carts];
        [self headerRefresh:nil];
    }else{
        [self.tableView displayNodes];
        [self updata];
    }
}
//
-(void)updata{
    CGFloat price = 0;
    NSInteger count = 0;
    NSArray *selected = [self.tableView visibleNodes];
    for (UITreeNode *node in selected) {
        if (node.select && node.level == 2) {
            id temp = [node.value objectForKey:@"product_detail"];
            if (temp && [temp isKindOfClass:NSDictionary.class]) {
                NSInteger c = [[node.value objectForKey:@"number"] integerValue];
                CGFloat p = [[temp objectForKey:@"price"] floatValue];
                price += c * p;
                count += c;
            }
        }
    }
    if (count > 0) {
        [self.countView setText:[NSString stringWithFormat:@"%ld", (long)count]];
        [self.priceView setText:[NSString stringWithFormat:@"￥%0.2f", price]];
        [self.discountView setText:[NSString stringWithFormat:@"￥%0.2f", price]];
        [self.commitView setTitle:[NSString stringWithFormat:@"结算(%ld)", (long)count] forState:UIControlStateNormal];
        [self.commitView setEnabled:YES];
    }else{
        [self.countView setText:@""];
        [self.priceView setText:@""];
        [self.discountView setText:@""];
        [self.commitView setEnabled:NO];
        [self.commitView setTitle:@"结算(0)" forState:UIControlStateNormal];
    }
}
@end
